#include "package.h"
#include <stdio.h>
#include <stdlib.h>

int main()
{
    /* 必须, cjson初始化 */
    CJson_hook_init();

    /* 填入传感器数据 */
    g_sensorData.do2 = 0.5;
    g_sensorData.eh = 0.7;
    g_sensorData.et = 0.3;
    g_sensorData.o2 = 1.6;
    g_sensorData.ph = 8.3;
    g_sensorData.pm10 = 1.2;
    g_sensorData.pm25 = 4.6;
    g_sensorData.wd = "SW";
    g_sensorData.ws = 5.6;
    g_sensorData.wt = 28.3056;
    g_sensorData.cdt = 2.6;
    g_sensorData.td = 8.9;

    /* 修改时间戳 */
    g_deviceItemsValue.timestamp = 1621142990;

    /* 将数据和设备ID等打包成Json字符串 */
    char *dataPacket = PackData2UpLoadJsonString(&g_deviceItemsValue, &g_sensorData);
    printf("%s\r\n", dataPacket);
    /* 释放空间 */
    free(dataPacket);

    /* 心跳包上传次数, 初次启动时为0 */
    g_deviceItemsValue.times++;
    /* 生成传感器上行心跳包 */
    char *heartbeat = CreatSensorHeartbeatPacket(&g_deviceItemsValue);
    printf("%s\r\n", heartbeat);
    /* 释放空间 */
    free(heartbeat);

    /* 填入继电器状态 */
    CtrItemsValue ctrItemsValue = {"60989ac0dc3d9af2c91dc293", 1, 0, 0};
    /* 生成控制设备上行心跳包 */
    char *ctrHeartbeat = CreatCtrHeartbeatPacket(&ctrItemsValue);
    printf("%s\r\n", ctrHeartbeat);
    /* 释放空间 */
    free(ctrHeartbeat);

    /* 填入下行反馈控制正确的设备(继电器)ID号, 以及控制成功或失败的状态 */
    ctrItemsValue.ctr_id = "60989ac0dc3d9af2c91dc293"; // 继电器的ID
    ctrItemsValue.result = 1;                          // 1是成功, 0是失败
    /* 生成控制设备执行反馈包 */
    char *resultPkg = CreatCtrResultPacket(&ctrItemsValue);
    printf("%s\r\n", resultPkg);
    /* 释放空间 */
    free(resultPkg);

    /* 控制器的开关状态 */
    g_switchStatus.S_No = 0;   //编号
    g_switchStatus.status = 0; //状态
    g_switchStatus.timestamp = 0;
    /* 模拟下行字串：打开通道4, 0->OFF, 1->ON */
    char *str = "{\"device_id\":\"60989ac0dc3d9af2c91dc293\",\"S_No\":4,\"status\":1,\"timestamp\":1620615248}";
    /* 解析下行字串包, 解析内容存至SwithStatus结构体中 */
    ParseDownString(&g_deviceItemsValue, str, &g_switchStatus);
    printf("(Old) S_No is :%d, status is : %d, timestamp is : %d\r\n", g_switchStatus.S_No, g_switchStatus.status,
           g_switchStatus.timestamp);

    /* 模拟下行字串：打开ID为60989ac0dc3d9af2c91dc293的控制设备(继电器), 0->OFF, 1->ON */
    char *downStr = "{\"ctrdevice_id\":\"60989ac0dc3d9af2c91dc293\",\"ctr\":1}";
    /* 解析下行字串包, 解析内容存至SwithStatus结构体中 */
    ParseCtrString(downStr, &g_switchStatus);
    printf("S_No is :%d, status is : %d\r\n", g_switchStatus.S_No, g_switchStatus.status);

    /* 时间戳转本地时间(年月日时分秒), 注意解析出来年+1900, 月份+1才是准确的时间*/
    LocalTime *nowTime = Timestamp2LocalTime(g_deviceItemsValue.timestamp);
    printf("%d-%d-%d %d:%d:%d\r\n", nowTime->tm_year + 1900, nowTime->tm_mon + 1, nowTime->tm_mday, nowTime->tm_hour,
           nowTime->tm_min, nowTime->tm_sec);

    /* 时间结构体转时间戳 */
    time_t timestamp = LocalTime2Timestamp(nowTime);
    free(nowTime);
    printf("%d\r\n", timestamp);

    return 0;
}
